* Begin log file
capture log close sublog
log using "$projdir/log/2_cps_build.txt", name(sublog) text replace

*-------------------------------------------------------------------------------
* Description: Clean and merge the 2009-2024 CPS data
* Author: Carl McPherson
*
* Updated: June 20, 2024
*-------------------------------------------------------------------------------

***********************************
* Build CPS data 
***********************************
clear 

gen year = .
save "$projdir/dta/build/cln/epi_cps_panel.dta", replace 

qui forv y = 2009/2023 {
	noi di "--`y' --"	
	use "$projdir/dta/build/cln/epi_cps_panel.dta", clear 
	append using "$projdir/dta/build/src/epi_cpsorg_2009_2024/epi_cpsorg_`y'.dta"
	save "$projdir/dta/build/cln/epi_cps_panel.dta", replace 
}

* For adding partial years
qui forv m = 1/5 {
	noi di "--2024: `m' --"	
	use "$projdir/dta/build/cln/epi_cps_panel.dta", clear 
	append using "$projdir/dta/build/src/epi_cpsorg_2009_2024/epi_cpsorg_2024_`m'.dta"
	save "$projdir/dta/build/cln/epi_cps_panel.dta", replace 
}

***********************************
* Merge with MW data 
***********************************
gen quarter = quarter(mdy(month,10,year))
gen quarterly_date = yq(year, quarter)

#delimit ; 
merge m:1 statefips quarterly_date using
	"$projdir/dta/build/src/mw_panel/mw_state_quarterly.dta"
	,
	keep(1 3) assert(1 2 3) nogen
	keepusing(max_mw)
;
#delimit cr 

***********************************
* Create new hourly wage variable
***********************************
gen hrwage = wage 
gen hours = hourslwt
gen usual_hours = hoursut

* Keep only employed non-self-employed workers
foreach v in hrwage hours usual_hours {
	replace `v' = . if lfstat != 1
	replace `v' = . if selfemp != 0 
}

* Deal with topcoding 
replace hours = 99 if hours > 99 & !mi(hours)
replace usual_hours = 99 if usual_hours > 99 & !mi(usual_hours)

* Remove imputed values
replace hrwage = . if a_earnhour == 1 | a_weekpay == 1
replace usual_hours = . if hoursvary == 1  

drop weekpay 
rename weekpay_noadj weekpay 
replace weekpay = . if a_weekpay == 1

***********************************
* Create emp variable 
***********************************
gen emp_raw = emp 

replace emp = . if selfemp != 0 

* Save
save "$projdir/dta/build/cln/epi_cps_panel.dta", replace

* Close log file
log close sublog
